﻿#include "maintask.h"
#include <QMetaType>
#include <QMutex>
#include<QTextCodec>
#include<iostream>
#include<QDebug>
#include<QTime>
#include<QCoreApplication>
#include "weighttask.h"
#include "rfid.h"
#include "intorfid.h"
using namespace std;
#define DISKPERCENT 30
#define READFREESPACE 50
#define SIXAXIS 49
#define FIVEAXIS 43
#define FOURAXIS 36
#define THREEAXIS 27
#define TWOAXIS 18
#define ZEROWEIGHT 10
#define OUTFACTORY 6
maintask::maintask(QObject *parent) :
    QThread(parent)
{
    qRegisterMetaType<QVariant>("QVariant"); //写在构造函数里
    IsUdp=false;
    Num=0;
    IsGetWeight=false;
    IsGetAxis=false;
    test=false;
    m_outtest=true;
}

void maintask::run(){
    InitPlate();
    qDebug() << "start highconfig " << endl;
    HighConfig();
    qDebug() << "end highconfig " << endl;

}

void maintask::IsdynamicWeight()
{
}

void maintask::IsStaticWeight()
{

}

void maintask::MaintaskRun()
{
    qDebug()<<"MaintaskRun";
    this->start();
}

void maintask::slotGet()
{
    qDebug()<<"maintask::slotGet()";
    IsUdp=true;
    //emit signalsetpar();
}

void maintask::LowConfig()
{

}

void maintask::Delay_MSec(int msec)
{
    QTime _Timer = QTime::currentTime().addMSecs(msec);

    while( QTime::currentTime() < _Timer )

    QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
//    QTime _Timer = QTime::currentTime();
//    QTime _NowTimer;
//    do{
//        _NowTimer=QTime::currentTime();
//    }while (_Timer.msecsTo(_NowTimer)<=msec);

}

void maintask::slotReciveRifd(const QString &cid)
{
    m_Rfid=cid;
}

void maintask::slotReciveOutRfid(const QString &cid)
{
    m_OutRfid=cid;
}

void maintask::slotReciveIntoRfid(const QString &cid)
{
    m_IntoRfid=cid;
}

void maintask::HighConfig()
{
    int i = 0;
    int runinfo = 0;
    QString headinfo("0");
    int normal=0; //0:normal 1:yichang

    QString rfid;
    QString rfidtail;
    QString outrfid_head,outrfid_tail;
    QString rfidinto;  //入场的读卡器

    WeightInfo w_Info, wu_info;
    CarType car_type;
    CardInfo carInfo;

    qDebug()<<"it is High Config";
    debugOut(QString("main task run!!!"));
    int RFIDPort=openPort("/dev/ttyS6",9600,8,1,"N");
    if(RFIDPort>0)
    {
        qDebug()<<QString("RFIDPORT Open Success");
    }
    RFID* RFIDdev = new RFID(RFIDPort);
    connect(RFIDdev,SIGNAL(signalToMainrfid(QString)),this,SLOT(slotReciveRifd(QString)));
    RFIDdev->start();

	//进场读卡器
    int RFIDPortIoto=openPort("/dev/ttyS3",9600,8,1,"N");
    if(RFIDPortIoto>0)
    {
        qDebug()<<QString("RFIDPORTInfo Open Success");
    }
    IntoRFID* RFIDIntodev = new IntoRFID(RFIDPortIoto);
    connect(RFIDIntodev,SIGNAL(signalToMainIntoRFID(QString)),this,SLOT(slotReciveIntoRfid(QString)));
    RFIDIntodev->start();

	//门口读卡器
    int OutRFIDPort=openPort("/dev/ttyS2",9600,8,1,"N");
    if(OutRFIDPort>0)
        qDebug()<<"OutRFID port open success!";
    OutRFID* OutRFIDDev=new OutRFID(OutRFIDPort);
    connect(OutRFIDDev,SIGNAL(signalToMainOutCardId(QString)),this,SLOT(slotReciveOutRfid(QString)));
    OutRFIDDev->start();


    int weightPort = openPort("/dev/ttyS5",1200/*systemFile::GetInstance()->weightBaudRate*/,8,1,"N");
    if(weightPort>0)
    {
        qDebug()<<QString("weightPort %2 open seucess").arg(systemFile::GetInstance()->weightBaudRate);

    }
    weightTask *weightDev = new weightTask(weightPort);
    weightDev->start();

    int CameraPort=openPort("/dev/ttyS1",9600,8,1,"N");
    if(CameraPort>0)
        qDebug()<<QString("CameraPort  open seucess");
    ContorlCamera* camera=new ContorlCamera(CameraPort);

    //初始化设置，清除is_down状态
    datebase::GetInstance()->ClearIsDown(&datebase::GetInstance()->mySql_db);

    while(1){
        //判断上车状态
        if( (weightDev->weightValue > 0) && (!m_Rfid.isEmpty()) )
        {
            normal=0;
            runinfo = 1;
            rfid = RFIDdev->CardId;
        }

        //判断离开状态
        if(runinfo>0)
        {
            if(  ( (!m_Rfid.isEmpty()) && (m_Rfid != rfid) )
                 ||(m_Rfid.isEmpty() && weightDev->weightValue==0) )
            {
                if(!m_Rfid.isEmpty())
                {
                    rfidtail = rfid;
                    datebase::GetInstance()->SureDown(&datebase::GetInstance()->mySql_db,rfidtail);
                    rfid = m_Rfid;
                }else
                {
                    datebase::GetInstance()->SureDown(&datebase::GetInstance()->mySql_db,rfid);
                }
                runinfo = 3;
            }
        }
        if(1 == runinfo) //1：上车
        {
            //qDebug()<<"rfid:"<<rfid<<"UP BANG!!!";
            if(rfid.indexOf("DE")!=-1 && rfid.indexOf("ED")!=-1)
            {
               // RFIDdev->AnalyzeCarInfo(rfid,carInfo,HashPlate);
                if(weightDev->weightValue>0)
                {
                    if(!test)
                    {
                        test=!test;
                        qDebug()<<"photo---------1-------";
                        camera->FirstOpenCamera();
                    }
                    if(w_Info.weightValue!=weightDev->weightValue)
                    {
                        debugOut(QString("main Task weight:%1").arg(weightDev->weightValue));
                        w_Info.weightValue=weightDev->weightValue;
                        if(!AnalyzeCarInfo(rfid,carInfo,HashPlate))
                            qDebug()<<"AnalyzeCarInfo Failed!";
                        else{
                            AnalyCarType(car_type,carInfo.carType);
                            if(!datebase::GetInstance()->IsHaveCardId(&datebase::GetInstance()->mySql_db,rfid))
                            {
                                datebase::GetInstance()->InserNewCardAndWeight(&datebase::GetInstance()->mySql_db,rfid,w_Info,carInfo,car_type);
                            }else
                            {
                                if(datebase::GetInstance()->IsNewInCar(&datebase::GetInstance()->mySql_db,rfid))
                                {
                                    datebase::GetInstance()->InserNewCardAndWeight(&datebase::GetInstance()->mySql_db,rfid,w_Info,carInfo,car_type);
                                }else
                                {
                                    //QString currtTime=QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
                                    QDateTime firstWeight;
                                    if(datebase::GetInstance()->SelectFirstTime(&datebase::GetInstance()->mySql_db,rfid,firstWeight))
                                    {
                                        if(firstWeight.secsTo(QDateTime::currentDateTime())> (60 * 60))
                                        {
                                            datebase::GetInstance()->UpdateOutFactoryStatus(&datebase::GetInstance()->mySql_db,rfid);
                                            datebase::GetInstance()->InserNewCardAndWeight(&datebase::GetInstance()->mySql_db,rfid,w_Info,carInfo,car_type);
                                        }
                                        else
                                        {
                                            if(datebase::GetInstance()->IsPrintList(&datebase::GetInstance()->mySql_db,rfid))
                                            {
                                                qDebug()<<"UPdate Weight!!!!";
                                                datebase::GetInstance()->IsDownWeight(&datebase::GetInstance()->mySql_db,rfid,w_Info,carInfo,car_type);

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
            //查找图片
            scanFile.updatePlate(rfid,false);
        }
        if(3 == runinfo) //3：离开
        {
            runinfo = 0;
            test=false;
        }

        if(m_OutRfid.indexOf("DE")!=-1 && m_OutRfid.indexOf("ED")!=-1)
        {
            if(outrfid_head!=m_OutRfid)
                outrfid_head=m_OutRfid;
        }
        if(outrfid_head.indexOf("DE")!=-1 && outrfid_head.indexOf("ED")!=-1)
        {
            outrfid_tail=outrfid_head;
            if( datebase::GetInstance()->IsOutFactory(&datebase::GetInstance()->mySql_db,outrfid_head))
            {
                qDebug()<<"photo---------2-------";
                camera->SecondOpenCamera();
                datebase::GetInstance()->SureOut(&datebase::GetInstance()->mySql_db,outrfid_head);
            }else
            {
                outrfid_head.clear();
            }
        }
        if(outrfid_tail.indexOf("DE")!=-1 && outrfid_tail.indexOf("ED")!=-1)
            scanFile.updatePlate(outrfid_tail,true);

//------------------------------------------------------------------------------------------------
        // into
        if( (weightDev->weightValue >0) && (!m_IntoRfid.isEmpty()) )
        {
            headinfo = "1";
            rfidinto = m_IntoRfid;
        }
        //into down
        if(headinfo == "1")
        {
            if(((weightDev->weightValue == 0) && (m_IntoRfid.isEmpty())) ||
               ((!m_IntoRfid.isEmpty()) && (m_IntoRfid != rfidinto)))
            {
                headinfo = "2";
            }
        }
        if(headinfo == "1")
        {

            if((weightDev->weightValue != wu_info.weightValue) && (weightDev->weightValue > 0) && (weightDev->weightValue < 21))
            {
                //new date
                wu_info.weightValue = weightDev->weightValue;
                //qDebug() << "weight exchange " << endl;
                if(rfidinto.indexOf("DE")!=-1 && rfidinto.indexOf("ED")!=-1)
                {
                    if(!AnalyzeCarInfo(rfidinto,carInfo,HashPlate))
                        qDebug()<<"AnalyzeCarInfo Failed!";
                    else
                    {
                        AnalyCarType(car_type,carInfo.carType);
                        qDebug() << "update ???" << endl;
                        if(!datebase::GetInstance()->IsUpdateCarTare(&datebase::GetInstance()->mySql_db,rfidinto))
                        {
                            qDebug() << "Into update Card info" << endl;
                            datebase::GetInstance()->updateHeadNewCar(&datebase::GetInstance()->mySql_db,rfidinto,wu_info);
                        }
                        else
                        {
                            qDebug() << "Into insert Card info" << endl;
                            datebase::GetInstance()->insertHeadNewCar(&datebase::GetInstance()->mySql_db,rfidinto,wu_info,carInfo,car_type);
                        }

                    }
                }
            }
        }
        if(headinfo == "2")
        {
            datebase::GetInstance()->InSetDownCar(&datebase::GetInstance()->mySql_db,rfidinto);
            headinfo = "0";
        }
        //error
        if(((m_IntoRfid.isEmpty()) && (m_Rfid.isEmpty())) && (weightDev->weightValue > 0))
        {
            if(wu_info.weightValue !=  weightDev->weightValue)
            {
                wu_info.weightValue =  weightDev->weightValue;
                if(datebase::GetInstance()->isHaveNone(&datebase::GetInstance()->mySql_db))
                {
                    qDebug() << "heve error thing weight update" << endl;
                    datebase::GetInstance()->undateNoneCarWht(&datebase::GetInstance()->mySql_db,wu_info);
                }
                else
                {
                    qDebug() << "heve error thing weight insert" << endl;
                    datebase::GetInstance()->insertLbNoneCarTare(&datebase::GetInstance()->mySql_db,wu_info);
                }
            }
        }

        if((wu_info.weightValue !=  weightDev->weightValue)  && (weightDev->weightValue == 0))
        {
            wu_info.weightValue =  weightDev->weightValue;
            qDebug() << "InSetDownNoneCar  Sql" << endl;
            datebase::GetInstance()->InSetDownNoneCar(&datebase::GetInstance()->mySql_db);
        }

        usleep(15000);
    }
}


void maintask::InitPlate()
{
    qDebug()<<"initplate";
    HashPlate.clear();
    HashPlate.insert("晋","01");
    HashPlate.insert("赣","02");
    HashPlate.insert("沪","03");
    HashPlate.insert("渝","04");
    HashPlate.insert("陕","05");
    HashPlate.insert("京","06");
    HashPlate.insert("豫","07");
    HashPlate.insert("津","08");
    HashPlate.insert("蒙","09");
    HashPlate.insert("新","10");
    HashPlate.insert("藏","11");
    HashPlate.insert("宁","12");
    HashPlate.insert("桂","13");
    HashPlate.insert("黑","14");
    HashPlate.insert("吉","15");
    HashPlate.insert("辽","16");
    HashPlate.insert("冀","17");
    HashPlate.insert("青","18");
    HashPlate.insert("鲁","19");
    HashPlate.insert("苏","20");
    HashPlate.insert("皖","21");
    HashPlate.insert("浙","22");
    HashPlate.insert("闽","23");
    HashPlate.insert("湘","24");
    HashPlate.insert("鄂","25");
    HashPlate.insert("粤","26");
    HashPlate.insert("琼","27");
    HashPlate.insert("甘","28");
    HashPlate.insert("贵","29");
    HashPlate.insert("云","30");
    HashPlate.insert("川","31");
//    QHashIterator<QString,QString> i(HashPlate);
//    while(i.hasNext())
//    {
//        i.next();
//        qDebug()<<"i.value="<<i.value()<<"i.key="<<i.key();
//    }
}

void maintask::AnalyCarType(CarType& type,int car_type)
{
    //CarType type;
    switch(car_type)
    {
        case 21:
            type.car_axis=2;
            type.max_weight=18;
            type.desc="21";
            type.car_shapes="12";
            break;
        case 31:
        case 32:
            type.car_axis=3;
            type.max_weight=27;
            type.desc="32";
            type.car_shapes="122-2";
            break;
        case 33:
        case 34:
            type.car_axis=3;
            type.max_weight=25;
            type.desc="33";
            type.car_shapes="112";
            break;
        case 41:
        case 42:
            type.car_axis=4;
            type.max_weight=36;
            type.desc="42";
            type.car_shapes="125-1";
            break;
        case 43:
        case 44:
            type.car_axis=4;
            type.max_weight=36;
            type.desc="43";
            type.car_shapes="125-2";
            break;
        case 45:
            type.car_axis=4;
            type.max_weight=31;
            type.desc="45";
            type.car_shapes="115";
            break;
        case 51:
        case 52:
        case 53:
        case 54:
            type.car_axis=5;
            type.max_weight=43;
            type.desc="53";
            type.car_shapes="155-2";
            break;
        case 55:
            type.car_axis=5;
            type.max_weight=42;
            type.desc="55";
            type.car_shapes="129";
            break;
        case 56:
        case 57:
            type.car_axis=5;
            type.max_weight=43;
            type.desc="57";
            type.car_shapes="1522";
            break;
        case 62:
        case 66:
        case 67:
        case 69:
            type.car_axis=6;
            type.max_weight=46;
            type.desc="67";
            type.car_shapes="1129";
            break;
        case 61:
        case 63:
        case 65:

            type.car_axis=6;
            type.max_weight=49;
            type.desc="65";
            type.car_shapes="159-3";
            break;
    }
    //return type;
}

bool maintask::AnalyzeCarInfo(QString rfid, CardInfo &car_info, QHash<QString, QString> &hash)
{
    if(rfid.count()!=24)
        return false;
    QString plate;
    QString proNum;
    QString city;
    QString num;
    QString tare;
    QString type;
    proNum=rfid.mid(2,2);
    city=rfid.mid(4,2);
    num=rfid.mid(6,12);
    type=rfid.mid(18,2);
    tare=rfid.mid(20,2);
    if(hash.isEmpty())
        qDebug()<<"HashPlate is Empty";
    QHashIterator<QString,QString> i(hash);
    while(i.hasNext())
    {
        i.next();
        if(i.value()==proNum)
            plate+=i.key();
    }
    city=QChar(city.toInt(NULL,16));
    plate+=city;
    QString num_1=num.left(2);
    if(num_1!="00")
        plate+="D";
    for(int i=0;i<5;i++)
    {
        QString num_1=num.mid(i*2+2,2);
        if(num_1>="00" && num_1<="09")
            num_1=num_1.right(1);
        else
            num_1=num_1.toInt(NULL,16);
        plate+=num_1;
    }
    car_info.plate=plate;
    car_info.carType=type.toInt(NULL,16);
    car_info.carTare=tare.toInt(NULL,16);
    if(car_info.carTare>21)
        car_info.carTare/=10;
    qDebug()<<"Out plate="<<car_info.plate;
    qDebug()<<"Out carType="<<car_info.carType;
    qDebug()<<"Out carTare="<<car_info.carTare;
    return true;
}

